package ccnGame;


/**
 * A Up and Down game program.
 * 
 * written by Gihoon Kim.
 * 
 * 
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import java.util.Random;

import ccnGame.CCNGameNet.CCNGameCallBack;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;



public class UpAndDown extends JFrame implements ActionListener, CCNGameCallBack{
	private static final long serialVersionUID = -8779269133035264361L;
	
	private int _number=0;
	
	//game window
	protected JTextArea  _messageArea= new JTextArea(10, 32);
	private JTextField  _textField= new JTextField(32);
	private String _current;
	private String nickname;
	private Iterator<String> _userlist;
	private int count;
	
	private final CCNGameNet _game;
	
	public UpAndDown(String namespace, String nick) throws MalformedContentNameStringException {
		nickname = nick;
		_game = new CCNGameNet(this, namespace, nickname);
				
		addWindowListener(
		           new WindowAdapter() {
		               public void windowClosing(WindowEvent e) {
		                   try {
							stop();
						} catch (IOException e1) {
							System.out.println("IOException shutting down listener: " + e1);
							e1.printStackTrace();
						}
		               }
		           }
	    );
		
		//make window
		_messageArea.setEditable(false);
		_messageArea.setBackground(Color.LIGHT_GRAY);
		_messageArea.setLineWrap(true);
		_textField.addActionListener(this);
		
		Container content = getContentPane();
		content.add(new JScrollPane(_messageArea), BorderLayout.CENTER);
		content.add(_textField, BorderLayout.SOUTH);
		
		//display the window
		setTitle("Up and Down: ["+namespace+"]");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
		_textField.requestFocusInWindow();
	}
	
	/**
	 * Process input to textfield.
	 */
	public void actionPerformed(ActionEvent e) {
		try{
			String newText = _textField.getText();
			if((null != newText) && (newText.length() >0)){
				if(_current.compareTo(nickname) ==0){
					if(typeOfnumber(newText)==-1){
						recvMessage("= Type number between 1~50 =\n");
					}
					else _game.sendMessage(newText);
				}
				else{
					recvMessage("Not you're turn\n");
				}
			}else{
				recvMessage("a Enter key makes network busy \n");
			}
		}
		catch(Exception e1){
			System.err.println("Exception input : "+e1.getClass().getName()+": "+e1.getMessage());
			e1.printStackTrace();
			recvMessage("Exception input : " + e1.getClass().getName()+": "+e1.getMessage());
		}
		_textField.setText("");
		_textField.requestFocusInWindow();
	}
	public int typeOfnumber(String a){
		int n = Integer.parseInt(a);
		if(n>=1 && n<=50){
			return 0;
		}
		else return -1;
	}
	/**
	 * Add a message to the output
	 * @param message
	 */
	public void recvMessage(String message){
		_messageArea.insert(message, _messageArea.getText().length());
		_messageArea.setCaretPosition(_messageArea.getText().length());
	}
	
	public void recvMessage(Message m1){
		String sender = m1.getName();
		String msg = m1.getMsg();
		String result;
			
		
		if(m1.getState() == Message.LOGIN_MESSAGE){			
			recvMessage(msg+"\n");
			_userlist = _game.getUserList();
			_current = _userlist.next();
			
			if(_current.compareTo(nickname) ==0) makeRandom();
			
			recvMessage(" START NEW GAME (1~50) \n");
			recvMessage(" == "+_current+" turn == \n");
		}
		else if(m1.getState()==Message.SHUTDOWN_MESSAGE){
			recvMessage(msg+"\n");
			_number=0;
			_userlist = _game.getUserList();
			_current = _userlist.next();
			
			if(_current.compareTo(nickname) ==0) makeRandom();
			
			recvMessage(" START NEW GAME (1~50) \n");
			recvMessage(" == "+_current+" turn == \n");
		}
		else if(m1.getState() == Message.SYSTEM_MESSAGE){
			
			recvMessage(msg+"\n");
			if(msg.compareTo("Correct")==0){
				_number=0;
				_userlist = _game.getUserList();
				_current = _userlist.next();
				
				if(_current.compareTo(nickname) ==0) makeRandom();
				
				recvMessage(" START NEW GAME (1~50) \n");
				recvMessage(" == "+_current+" turn == \n");
			}else{
				if(_userlist.hasNext()){
					_current = _userlist.next();
				}
				else{
					_userlist = _game.getUserList();
					_current = _userlist.next();
				}
				recvMessage(" == "+_current+" turn == \n");
			}
		}
		else{			
			result = "["+sender+"] "+ msg+"\n"; 
			recvMessage(result);
			if(_number!=0){
				String game_result = compareProcess(msg);
				recvMessage(game_result);
				try {
					_game.sendMessage("System::::"+ game_result);
					recvMessage("wow\n");
				} catch (ContentEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public String compareProcess(String s1){
		int n = Integer.parseInt(s1); // n is compare with _number
		
		if(_number>n) return "Up";
		else if(_number<n) return "Down";
		else return "Correct";
	}
	public void makeRandom(){
		Random oRandom = new Random();
		_number = oRandom.nextInt(50)+1;
	}
	
	public void setNumber(int n){
		_number = n;
	}
	
	public int getNumber(){
		return _number;
	}
	
	public static void usage(){
		System.err.println("usage : UpAndDown <ccn URl>");	
	}
	/*
	public static void main(String[] args){
		if(args.length!=1){
			usage();
			System.exit(-1);
		}
		BaseballGame client;
		try{
			client = new UpAndDown(args[0]);
			client.start();
		}catch (MalformedContentNameStringException e) {
			System.err.println("Not a valid ccn URI: " + args[0] + ": " + e.getMessage());
			e.printStackTrace();
		} catch (ConfigurationException e) {
			System.err.println("Configuration exception running BaseballGame: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("IOException handling BaseballGame messages: " + e.getMessage());
			e.printStackTrace();
		}
		
		
	}*/
	/**
	 * Called by window thread when window is closed.
	 */
	protected void stop() throws IOException{
		_game.shutDown();
	}
	
	/**
	 * This blocks until _game.shutdown() called
	 * @throws IOException 
	 * @throws MalformedContentNameStringException 
	 * @throws ConfigurationException 
	 */
	protected void start() throws ConfigurationException, MalformedContentNameStringException, IOException {
		_game.connect();
	}
	
}
